<template>
	<div>
		<u-navbar leftIcon="" placeholder title="通讯录"></u-navbar>
		<!-- v-if="!contactSearchingStatus" -->
		<ul class="TUI-contact-list">
			<li class="TUI-contact-list-item">
				<div class="TUI-contact-list-item-main" >
					<header class="TUI-contact-list-item-header"
						@click="toggleCurrentContactList">
						<div class="TUI-contact-list-item-header-left">
							<image class="apply-friend" :src="applyFriendImg" />
							<div>{{ TUITranslateService.t(`TUIContact.${contactListMap.friendApplicationList.title}`) }}</div>
						</div>
						<div class="TUI-contact-list-item-header-right">
							<span class="TUI-contact-list-item-header-right-unread"  v-if="contactListMap.friendApplicationList.unreadCount">
								{{ contactListMap.friendApplicationList.unreadCount }}
							</span>
						</div>
					</header>
				</div>
				<div class="TUI-contact-list-item-main" >
					<u-index-list :indexList="indexList" :customNavHeight="60">
						<template v-for="(item, index) in contactListMap.friendList.list">
							<u-index-item>
								<u-index-anchor v-show="item.list.length" :text="item.key"></u-index-anchor>
								<div v-for="(contactListItem, contactListItemKey) in item.list"
									:key="contactListItemKey" class="TUI-contact-list-item-main-item"
									:class="['selected']" @click="selectItem(contactListItem)">
									
									<ContactListItem :item="contactListItem" :list="contactListMap.friendList.list"
										:displayOnlineStatus="displayOnlineStatus"
										:userOnlineStatusMap="userOnlineStatusMap" />
								</div>
							</u-index-item>
						</template>
					</u-index-list>

				</div>
			</li>
		</ul>
		<!-- 通讯录搜索返回 -->
		<!-- <ul class="TUI-contact-list" v-else>
			<li class="TUI-contact-list-item" v-for="(item, key) in contactSearchResult" :key="key">
				<div class="TUI-contact-search-list" v-if="item.list[0]">
					<div class="TUI-contact-search-list-title">
						{{ TUITranslateService.t(`TUIContact.${item.label}`)}}
					</div>
					<div v-for="listItem in item.list" class="TUI-contact-search-list-item" :class="['selected']"
						@click="selectItem(listItem)">
						<ContactListItem :item="listItem" :list="item.list" />
					</div>
				</div>
			</li>
			<div class="TUI-contact-search-list-default" v-if="isContactSearchNoResult">
				{{ TUITranslateService.t("TUIContact.无搜索结果") }}
			</div>
		</ul> -->
	</div>
</template>
<script setup lang="ts">
	import {
		TUITranslateService,
		TUIStore,
		StoreName,
		IGroupModel,
		TUIFriendService,
		Friend,
		FriendApplication,
		TUIUserService,
	} from "@tencentcloud/chat-uikit-engine";
	import { TUIGlobal } from "@tencentcloud/universal-api";
	import TUICore, { TUIConstants } from "@tencentcloud/tui-core";
	import { sortByFirstLetter } from "../../../utils/checkLogin.js";
	import { ref, computed, onMounted, onUnmounted } from "../../../adapter-vue";
	// import Icon from "../../common/Icon.vue";
	// import downSVG from "../../../assets/icon/down-icon.svg";
	// import rightSVG from "../../../assets/icon/right-icon.svg";
	import {
		IContactList,
		IContactSearchResult,
		IBlackListUserItem,
		IUserStatus,
		IUserStatusMap,
	} from "../../../interface";
	import ContactListItem from "./contact-list-item/index.vue";
	import { searchGroups } from "components/TUISearch/utils.js";
	import applyFriendImg  from "../../../assets/icon/apply-friend.png";

	const currentContactListKey = ref<string>("");
	const currentContactInfo = ref<any>({});
	let indexList = ref<any>([]);
	const indexListArr = () => {
		const arr : any = [];
		const charCodeOfA = 'A'.charCodeAt(0);
		for (let i = 0; i < 26; i++) {
			arr.push(String.fromCharCode(charCodeOfA + i));
		}
		arr.push('*')
		indexList.value = arr
	}


	const contactListMap = ref<IContactList>({
		friendApplicationList: {
			key: 'friendApplicationList',
			title: "新的朋友",
			list: [] as Array<FriendApplication>,
			unreadCount: 0,
		},
		// blackList: {
		//   key: 'blackList',
		//   title: "黑名单",
		//   list: [] as Array<IBlackListUserItem>,
		// },
		// groupList: {
		//   key: 'groupList',
		//   title: "我的群聊",
		//   list: [] as Array<IGroupModel>,
		// },
		friendList: {
			key: 'friendList',
			title: "我的好友",
			list: [] as Array<Friend>,
		},
	});
	const contactSearchingStatus = ref<boolean>(false);
	const contactSearchResult = ref<IContactSearchResult>();
	const displayOnlineStatus = ref<boolean>(false);
	const userOnlineStatusMap = ref<IUserStatusMap>();

	const isContactSearchNoResult = computed(() : boolean => {
		return (
			!contactSearchResult?.value?.user?.list[0] &&
			!contactSearchResult?.value?.group?.list[0]
		);
	});

	onMounted(() => {
		indexListArr()
		TUIStore.watch(StoreName.APP, {
			enabledCustomerServicePlugin: onCustomerServiceCommercialPluginUpdated,
		});

		// TUIStore.watch(StoreName.GRP, {
		//   groupList: onGroupListUpdated,
		// });

		// TUIStore.watch(StoreName.USER, {
		//   userBlacklist: onUserBlacklistUpdated,
		//   displayOnlineStatus: onDisplayOnlineStatusUpdated,
		//   userStatusList: onUserStatusListUpdated,
		// });

		TUIStore.watch(StoreName.FRIEND, {
			friendList: onFriendListUpdated,
			// friendApplicationList: onFriendApplicationListUpdated,
			friendApplicationUnreadCount: onFriendApplicationUnreadCountUpdated,
		});

		TUIStore.watch(StoreName.CUSTOM, {
			currentContactSearchingStatus: onCurrentContactSearchingStatusUpdated,
			currentContactSearchResult: onCurrentContactSearchResultUpdated,
		});
	});

	onUnmounted(() => {
		TUIStore.unwatch(StoreName.APP, {
			enabledCustomerServicePlugin: onCustomerServiceCommercialPluginUpdated,
		});

		// TUIStore.unwatch(StoreName.GRP, {
		//   groupList: onGroupListUpdated,
		// });

		// TUIStore.unwatch(StoreName.USER, {
		//   userBlacklist: onUserBlacklistUpdated,
		//   displayOnlineStatus: onDisplayOnlineStatusUpdated,
		//   userStatusList: onUserStatusListUpdated,
		// });

		TUIStore.unwatch(StoreName.FRIEND, {
			friendList: onFriendListUpdated,
			// friendApplicationList: onFriendApplicationListUpdated,
			friendApplicationUnreadCount: onFriendApplicationUnreadCountUpdated,
		});

		TUIStore.unwatch(StoreName.CUSTOM, {
			currentContactSearchingStatus: onCurrentContactSearchingStatusUpdated,
			currentContactSearchResult: onCurrentContactSearchResultUpdated,
		});
	});

	function updateCurrentContactInfoFromList(list : Array<any>, type : string) {
		if (
			!currentContactInfo?.value?.userID &&
			!currentContactInfo?.value?.groupID
		) {
			return;
		} else if (
			currentContactInfo?.value?.groupID &&
			(type === currentContactListKey.value || contactSearchingStatus.value)
		) {
			currentContactInfo.value = list?.find(
				(item : any) =>
					item?.groupID && item?.groupID === currentContactInfo?.value?.groupID
			);
			TUIStore.update(StoreName.CUSTOM, "currentContactInfo", currentContactInfo.value);
		} else if (
			currentContactInfo?.value?.userID &&
			(type === currentContactListKey.value || contactSearchingStatus.value)
		) {
			currentContactInfo.value = list?.find(
				(item : any) =>
					item?.userID && item?.userID === currentContactInfo?.value?.userID
			);
			TUIStore.update(StoreName.CUSTOM, "currentContactInfo", currentContactInfo.value);
		}
	}

	function toggleCurrentContactList() {
		TUIGlobal?.navigateTo({
			url: "/pages/TUIKit/components/TUIContact/contact-new/index",
		});
		TUIFriendService.setFriendApplicationRead();
	}

	function selectItem(item : any) {
		currentContactInfo.value = item;
		// 单独处理：
		// 对于 搜索列表 中 某结果，查看 contactInfo 详情前，需要对于“已在群组列表/已在好友列表” 的情况进行数据更新，已获得更详细的信息
		if (contactSearchingStatus.value) {
			let targetListItem;
			if (currentContactInfo?.value?.userID) {
				targetListItem = contactListMap?.value?.friendList?.list?.find(
					(item : any) => item?.userID === currentContactInfo?.value?.userID
				);
			} else if (currentContactInfo?.value?.groupID) {
				targetListItem = contactListMap?.value?.groupList?.list?.find(
					(item : any) => item?.groupID === currentContactInfo?.value?.groupID
				);
			}
			if (targetListItem) {
				currentContactInfo.value = targetListItem;
			}
		}
		// 更新数据
		TUIStore.update(StoreName.CUSTOM, "currentContactInfo", currentContactInfo.value);
	}

	function onDisplayOnlineStatusUpdated(status : boolean) {
		displayOnlineStatus.value = status;
	}

	function onUserStatusListUpdated(list : Map<string, IUserStatus>) {
		if (list?.size > 0) {
			userOnlineStatusMap.value = Object.fromEntries(list?.entries());
		}
	}

	function onCustomerServiceCommercialPluginUpdated(isEnabled : boolean) {
		if (!isEnabled) {
			return;
		}

		/// 客户购买客服插件后 engine 通过商业化能力位更新将 enabledCustomerServicePlugin 设置为 true
		const contactListExtensionID = TUIConstants.TUIContact.EXTENSION.CONTACT_LIST.EXT_ID;
		const tuiContactExtensionList = TUICore.getExtensionList(contactListExtensionID);

		const customerData = tuiContactExtensionList.find((extension : any) => {
			const { name, accountList = [] } = extension.data || {};
			return name === 'customer' && accountList.length > 0;
		});

		if (customerData) {
			const { data, text } = customerData;
			const { accountList } = (data || {}) as { accountList : string[] };

			TUIUserService.getUserProfile({ userIDList: accountList })
				.then((res) => {
					if (res.data.length > 0) {
						const customerList = {
							title: text,
							list: res.data.map((item : any) => {
								return {
									...item,
									infoKeyList: [],
									btnKeyList: ["enterC2CConversation"],
								};
							}),
							key: "customerList",
						};
						contactListMap.value = { ...contactListMap.value, customerList };
					}
				})
				.catch((error) => {
					if (error.code === 3003) {
						uni.showToast({
							title: "聊天账号已在其他设备登录",
							icon: "none",
						})
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/tabbar/index'
							})
						}, 1000)
						return null
					}
				
					uni.showToast({
						title: "查找失败：" + error?.message,
						icon: "none",
						duration: 1000,
					});
				});
		}
	}

	function onGroupListUpdated(groupList : Array<IGroupModel>) {
		contactListMap.value.groupList.list = groupList;
		updateCurrentContactInfoFromList(contactListMap.value.groupList.list, "groupList");
	}

	function onUserBlacklistUpdated(userBlacklist : Array<IBlackListUserItem>) {
		contactListMap.value.blackList.list = userBlacklist;
		updateCurrentContactInfoFromList(contactListMap.value.blackList.list, "blackList");
	}

	function onFriendApplicationUnreadCountUpdated(friendApplicationUnreadCount : number) {
		contactListMap.value.friendApplicationList.unreadCount = friendApplicationUnreadCount;
	}

	function onFriendListUpdated(friendList : Array<Friend>) {
		// contactListMap.value.friendList.list = friendList;
		// 按照字母排序列表
		contactListMap.value.friendList.list = sortByFirstLetter(friendList);
		updateCurrentContactInfoFromList(contactListMap.value.friendList.list, "friendList");
	}


	// function onFriendApplicationListUpdated(friendApplicationList : Array<FriendApplication>) {
	// 	contactListMap.value.friendApplicationList.list = friendApplicationList;
	// 	updateCurrentContactInfoFromList(contactListMap.value.friendApplicationList.list, "friendApplicationList");
	// }

	function onCurrentContactSearchResultUpdated(searchResult : IContactSearchResult) {
		contactSearchResult.value = searchResult;
	}

	function onCurrentContactSearchingStatusUpdated(searchingStatus : boolean) {
		contactSearchingStatus.value = searchingStatus;
		currentContactInfo.value = {};
		currentContactListKey.value = "";
		TUIStore.update(StoreName.CUSTOM, "currentContactInfo", currentContactInfo.value);
	}
</script>

<style lang="scss" scoped src="./style/index.scss"></style>
<style lang="scss">
	uni-page-body,
	html,
	body,
	page {
	  background: #fff;
	}
	.apply-friend {
		width: 50px;
		height: 50px;
		margin-right: 10px;
	}

	.TUI-contact-list-item-header {
		// border-bottom: 1px solid #ececec;
		padding: 8px 0;
		position: relative;
		&:after{
			width: calc(100% - 60px);
			bottom: 0;
			right: 0;
			position: absolute;
			content: '';
			background:#ececec ;
			height: 1px;
		}
		.TUI-contact-list-item-header-right{
			position: absolute;
			left: 40px;
		}
		
	}

	.TUI-contact-list-item-main {
		padding: 0 30px 0 15px;
	}

	::v-deep {
		.u-index-anchor.u-border-bottom {
			background: #fff !important;
			border-bottom-width: 0 !important;
			padding-left: 0 !important;
		}
	}
</style>